package Action.Sys;

import Bean.BookInfoEntity;
import Bean.LoanBookLogRecord;
import Bean.Log.HistoricalData;
import Bean.Log.OrderLog;
import Bean.Log.SystemLogEntity;
import Bean.Log.UserLogEntity;
import Bean.UserinfoEntity;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.io.FileUtils;
import org.hibernate.Session;
import tools.HibernateTools;
import tools.TimeTools;

import java.io.File;
import java.sql.Timestamp;
import java.util.*;

public  class Setting {


    public static final String UserLog_flag_UserLogin="用户登录";
    public static final String UserLog_flag_UserLogout="用户退出";
    public static final String UserLog_flag_UserAdd="用户注册";
    public static final String UserLog_flag_UserUpdateUserInfo="用户更新资料";
    public static final String UserLog_flag_ManagerUpdateUserInfo="管理员修改用户信息";


    public static final String UserLog_flag_UserBorrowBook="用户借书";
    public static final String UserLog_flag_UserReturnBook="用户还书";
    public static final String SystemLog_flag_AddBook="图书添加";
    public static final String SystemLog_flag_AddUser="用户添加";
    public static final String SystemLog_flag_DelUser="用户删除";
    public static final String SystemLog_flag_ManagerUserData="管理用户信息";
    public static final String SystemLog_flag_AltUserData="修改用户信息";
    public static final String SystemLog_flag_AltManagerData="更新管理员资料";
    public static final String SystemLog_flag_ManagerBookData="管理图书信息";
    public static final String SystemLog_flag_AltBookData="修改图书信息";
    public static final String SystemLog_flag_DelBookData="删除图书";



    public static final String LoanBook_state_reservation="预约";
    public static final String LoanBook_state_need_Return="待归还";
    public static final String LoanBook_state_need_TimeOut="超时待归还";
    public static final String LoanBook_state_closed="订单完成";
    public static final String LoanBook_state_cancel="订单取消";


    //可配置的系统设置
    public static  int LoanBook_Max_Num=5;
    public static  int LoanBookNum_Max_Num=5;//借书最大数量
    public static  int LoanBook_Max_day=7;
    public static  int LoanBook_Min_day=1;



    public static long SYS_min_cache_time=3;//磁盘缓存检查最小时间间隔
    public static long SYS_cache_Max_time=15;//缓存文件最大有效时间
    public static long SYS_cache_MaxSize=50;//磁盘文件允许最大占用空间大小---软要求(提前触发缓存清理)
    public static long SYS_cache_Model=2;//1全新模式(每次都从数据库中加载def) 2 在SYS_min_cache_time时间内本地文件优先 3本地优先

    public static int Sys_database_clear_log_day=31;

    public static long clear_cache(){//main--来自高金磊
        File file=new File("H:\\桌面大文件\\毕业设计\\BookLoanSystem\\out\\artifacts\\BookLoanSystem_war_exploded\\cache");
        long size = FileUtils.sizeOfDirectory(file);

        //两级目录(def)
        for (File listFile : file.listFiles()) {
//            ZipFile zip_file = new ZipFile(file);
//            ZipEntry entry = zip_file.getEntry("file.zip");
//            entry.setLastAccessTime(FileTime.fromMillis(100000));//获取最后的访问时间
            if (listFile.isDirectory()){
                for (File file1 : listFile.listFiles()) {
                    if ((System.currentTimeMillis()-file1.lastModified())>SYS_cache_Max_time*60*1000){
                        file1.delete();
                    }
                }
            }
            else {
                if ((System.currentTimeMillis()-listFile.lastModified())>SYS_cache_Max_time*60*1000){
                    listFile.delete();
                }
            }

        }
        size-=FileUtils.sizeOfDirectory(file);
        size/=1024;
        System.out.println("缓存清理已经执行释放空间:"+size+" KB");
        if (size!=0) {
            Integer administratorid = null;
            try {
                administratorid =(Integer) ActionContext.getContext().getSession().get("administratorid");
            } catch (Exception e) {
               administratorid=-1;//当前没有用户
            }
            if (administratorid==null){
                administratorid=-1;
            }
            SystemLogEntity.addLog((Integer) administratorid, null, "缓存清理成功释放空间:" + size + " KB");
        }

       return  size;
    }

    public static double cache_size(){
        File file=new File("H:\\桌面大文件\\毕业设计\\BookLoanSystem\\out\\artifacts\\BookLoanSystem_war_exploded\\cache");
//        File file=new File("out/artifacts/BookLoanSystem_war_exploded/cache");
        double size = FileUtils.sizeOfDirectory(file);
        return size/1024/1024;
    }
    public static double database_size(){
        File file=new File("E:\\mysql-5.7.33-winx64\\data\\bookloansystem");
        double size = FileUtils.sizeOfDirectory(file);
        return  size/1024/1024;
    }
    public static double project_size(){
//        File file=new File(System.getProperty("user.dir"));//这是tomcat里面的
        File file=new File("H:\\桌面大文件\\毕业设计\\BookLoanSystem\\out");
        double size = FileUtils.sizeOfDirectory(file);
        return  size/1024/1024;
    }
    public static double All_size(){
        return  project_size()+database_size();
    }

    public static boolean cache_comment_size(){
        //对数据库的图书进行扫描,更新评论,删除无用评论
        Session session = HibernateTools.getSession();
        ArrayList<Integer> books_id= (ArrayList<Integer>) session.createQuery("select distinct bookId from BookCommentEntity").getResultList();

        for (Integer integer : books_id) {
            BookInfoEntity bookInfoEntity=session.get(BookInfoEntity.class, integer);
            if (bookInfoEntity==null){
                //图书不存在
                continue;
            }
            long size=(Long) session.createQuery("select count (*) from BookCommentEntity where bookId="+integer)
                    .list().get(0);
            bookInfoEntity.setComment_size((int) size);
            session.update(bookInfoEntity);
        }
//        HibernateTools.commit(session);
        return true;
    }

    static List<Object[]> TopLoanUser;
    static Long pre_time;
    public static List<Object[]> getTopLoanUser(int size,Long time){//time是向上传递
        if (TopLoanUser==null||TopLoanUser.size()==0||System.currentTimeMillis()-pre_time>2*60*60*1000){//两个小时更新一次
            //需要更新
            pre_time=System.currentTimeMillis();
            Session session = HibernateTools.getSession();
            TopLoanUser=new LinkedList<>();
            List<Object[]> TopLoanUser_middle=new LinkedList<>();
            List<UserinfoEntity> userinfoEntities=session.createQuery("from UserinfoEntity").getResultList();
            for (UserinfoEntity userinfoEntity : userinfoEntities) {
                Long middle= (Long) session.createQuery("select count (*) from LoanBookLogRecord where  state like ?1 and userId=?2")
                        .setParameter(1,Setting.LoanBook_state_closed)
                        .setParameter(2,userinfoEntity.getId())
                        .getResultList().get(0);
                TopLoanUser_middle.add(new Object[]{userinfoEntity,middle});
            }
            Collections.sort(TopLoanUser_middle,new Comparator<Object[]>(){

                @Override
                public int compare(Object[] o1, Object[] o2) {
                    return (int) ((Long)o2[1]-(Long) o1[1]);
                }
            });//排序
            for (Object[] objects : TopLoanUser_middle) {
                if (TopLoanUser.size()<size){
                    TopLoanUser.add(objects);
                }
            }
//            HibernateTools.commit(session);// 静态的没有session
        }
        time=pre_time;
        return TopLoanUser;
    }

    /**
     * 执行数据库整理--只清理过期数据
     * @return 整理结果--删除多少条记录
     * @throws Exception
     */
    public static String database_clear() throws Exception{
        //不做无效日志的清除--请在用户或者图书删除时主动清理

        long currentTimeMillis=System.currentTimeMillis();
        //读取设置
        int days=Setting.Sys_database_clear_log_day;//日志有效日期def=31;
        Timestamp timestamp = TimeTools.formatTime(days);//这么多天前的时间戳
        //数据库清理逻辑
        Session session = HibernateTools.getSession();
        //历史记录清除
        List<HistoricalData> historicalDataList=session.createQuery("from HistoricalData where timestamp < '"+timestamp+"'").getResultList();
        int num=historicalDataList.size();
        for (HistoricalData historicalData : historicalDataList) {
            session.remove(historicalData);
        }
        //用户日志
        List<UserinfoEntity> userinfoEntities=session.createQuery("from UserinfoEntity ").getResultList();
        for (UserinfoEntity userinfoEntity : userinfoEntities) {
            List<UserLogEntity> userLogEntities=session.createQuery("from UserLogEntity where userId="+userinfoEntity.getId()+" order by id desc ").getResultList();
            if (userLogEntities.size()<10){
                //日志数量太少不进行清理
                continue;
            }else {
                for (int i = 0; i < 10; i++) {
                    //保护最近的10条记录
                    userLogEntities.remove(0);
                }
            }

            for (UserLogEntity userLogEntity : userLogEntities) {
                if (TimeTools.Remainder_days(userLogEntity.getTimestamp())<-days){
                    //日期太久
                    session.remove(userLogEntity);
                    num++;
                }
            }
        }
        //系统日志
        List<SystemLogEntity> systemLogEntities=session.createQuery("from SystemLogEntity where logData <'"+timestamp+"'").getResultList();

        for (SystemLogEntity systemLogEntity : systemLogEntities) {
            session.remove(systemLogEntity);
            num++;
        }
        //订单和订单日志
        for (UserinfoEntity userinfoEntity : userinfoEntities) {
            //获取用户订单--包括已取消
            List<LoanBookLogRecord> loanBookLogRecords=session.createQuery("from LoanBookLogRecord where userId=?1 and " +
                    "(state like ?2 or state like ?3)")
                    .setParameter(1,userinfoEntity.getId())
                    .setParameter(2,"'"+Setting.LoanBook_state_closed+"'")
                    .setParameter(3,"'"+Setting.LoanBook_state_cancel+"'")
                    .getResultList();
            for (LoanBookLogRecord loanBookLogRecord : loanBookLogRecords) {
                if (TimeTools.Remainder_days(loanBookLogRecord.getLoanTime())<-days*6){
                    //超过六个月的订单以及其日志
                    session.remove(loanBookLogRecord);
                    List<OrderLog> orderLogs=session.createQuery("from OrderLog where orderid=?1")
                            .setParameter(1, loanBookLogRecord.getId())
                            .getResultList();
                    for (OrderLog orderLog : orderLogs) {
                        session.remove(orderLog);
                        num++;
                    }
                    num++;
                }
            }

        }

//        HibernateTools.commit(session);//交付给调用者
        return "清理成功,共计清理"+num+"条日志,耗时"+((int)(System.currentTimeMillis()-currentTimeMillis)/1000)+"s";
    }
    public static void main(String arg[]){//main--来自高金磊

        //更新评论
//        cache_comment_size();
//        getTopLoanUser(100, 0L);
//        System.err.println(project_size());
//        try {
//            System.out.println(database_clear());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
    

}


